package com.ebring.shareEducation.controller;

import com.ebring.shareEducation.bean.User;
import com.ebring.shareEducation.bean.response.UserRsp;
import com.ebring.shareEducation.bean.response.UserTlent;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import com.ebring.shareEducation.dao.UserMapper;
import com.ebring.shareEducation.service.UserService;
import com.ebring.shareEducation.utils.*;
import com.github.pagehelper.PageHelper;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@RestController
 @Api(value = "用户对象管理" ,tags = {"用户对象管理接口"})
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;


    @PostMapping("/user/idAuth")
    @ApiOperation(value="身份认证", notes="身份认证")
    @ApiImplicitParam(paramType="query",name = "user", value = "用户详细实体user", required = true, dataType = "User")
    public RspMsg idAuth(User user) {
        return userService.authId(user);
    }

    /**
     * 修改用户密码
     *
     * @param oldPassword 原密码
     * @param newPassword 新密码
     * @param token       用户信息
     * @return map
     */
    @PostMapping("/user/changePassword")
    @ApiOperation(value="修改用户密码", notes="修改用户密码")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "oldPassword", value = "旧密码", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType="query",name = "newPassword", value = "新密码", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType="query",name = "validDate", value = "有效时间", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query",name = "token", value = "判断用户是否登录", required = true, dataType = "String")
    })

    public RspMsg<User> changePassword(String oldPassword, String newPassword, String validDate, String token) {

        return userService.changePassword(oldPassword, newPassword, validDate, token);
    }

    /**
     * 添加用户
     *
     * @param
     * @return 插入成功结果
     */
    @PostMapping("/user/insert")
    @ApiOperation(value="添加用户", notes="根据User对象添加用户")
    @ApiImplicitParam(paramType="query",name = "user", value = "用户详细实体user", required = true, dataType = "User")
    public RspMsg<User> insertUser(User user) {
        return userService.insertUser(user);
    }

    /**
     * 更新用户
     *
     * @param
     * @return 更新成功的结果
     */
    @PostMapping("/user/update")
    @ApiOperation(value="更新用户", notes="根据User对象更新用户")
    @ApiImplicitParam(paramType="query",name = "user", value = "用户详细实体user", required = true, dataType = "User")
    public RspMsg<User> updateUser(User user) {

        return userService.updateUser(user);
    }

    /**
     * 根据用户ID查找用户
     *
     * @param userId 用户ID
     * @return
     */
    @GetMapping("/user/selectById")
    @ApiOperation(value="根据用户ID查找用户", notes="根据用户ID查找用户")
    @ApiImplicitParam(paramType="query",name = "userId", value = "用户id", required = true, dataType = "String")
    public RspMsg<User> selectUserByUserId(String userId) {
        return userService.selectUserByUserId(userId);
    }

    /**
     * 查找所有用户
     *
     * @param
     * @return
     */
    @GetMapping("/user/selectusers")

    @ApiOperation(value="获取用户列表", notes="获取用户列表")
    public RspMsg<UserRsp> selectUserfind() {
        return userService.selectUsersfind();
    }

    /**
     * 批量删除用户
     *
     *
     * @param userId 用户Id
     * @return 删除成功的数量
     */
    @GetMapping("/user/delete")
    @ApiOperation(value="批量删除用户", notes="批量删除用户")
    @ApiImplicitParam(paramType="query",name = "userId", value = "用户id", required = true, dataType = "String[]")
    public RspMsg<User> DeleteUsers(String[] userId) {

        return userService.DeleteUsers(userId);

    }






    /**
     * 解析token字段
     *
     * @param token
     * @return user对象
     */

    @PostMapping("/user/token")
    @ApiOperation(value="解析token字段", notes="解析token字段")
    @ApiImplicitParam(paramType="query",name = "token", value = "token", required = true, dataType = "String")
    public RspMsg<User> token(String token) {

        RspMsg rspMsg = new RspMsg();

        if ("".equals(token)) {
            rspMsg.setError();
            rspMsg.setMsg("token为空，请重新输入");
            return rspMsg;
        }

        User user = JwtUtils.unsign(token, User.class);
        rspMsg.setOK();
        rspMsg.setResult(user);
        return rspMsg;
    }

    /**
     * 查询机构下面所有的用户
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/user/selectUsers")
    @ApiOperation(value="查询机构下面所有的用户", notes="查询机构下面所有的用户")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "pageNum", value = "页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType="query",name = "pageSize", value = "总页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType="query",name = "userId", value = "用户id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query",name = "username", value = "用户名称", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query",name = "branchId", value = "部门编号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query",name = "institutionName", value = "部门名称", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query",name = "roleId", value = "角色编号", required = true, dataType = "String")
    })
    public RspMsg<UserRsp> selectUsers(Integer pageNum, Integer pageSize, String userId, String username, String branchId, String institutionName, String roleId, HttpServletRequest request) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 5;
        }
        if ("001".equals(roleId) || "0004".equals(roleId)) {
            branchId = null;
        }
        PageHelper.startPage(pageNum, pageSize);
        return userService.selectUsers(userId, branchId, username, institutionName);
    }

    /**
     * 根据用户id查询用户角色的基本信息
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/user/findUserByuserId")
    @ApiOperation(value="根据用户id查询用户角色的基本信息", notes="根据用户id查询用户角色的基本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "pageNum", value = "页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType="query",name = "pageSize", value = "总页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType="query",name = "userId", value = "用户id", required = true, dataType = "String"),
    })
    public RspMsg<UserRsp> findUserByuserId(Integer pageNum, Integer pageSize, String userId, HttpServletRequest request) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 5;
        }
        PageHelper.startPage(pageNum, pageSize);
        return userService.findUserByuserId(userId);


    }


    /**
     * 用户管理模块模糊时查询
     *

     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/user/findUser")
    @ApiOperation(value="用户管理模块模糊时查询", notes="用户管理模块模糊时查询")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "pageNum", value = "页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType="query",name = "pageSize", value = "总页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType="query",name = "UserRsp", value = "用户显示UserRsp", required = true, dataType = "UserRsp"),
    })
    public RspMsg<List<UserRsp>> findUser(UserRsp userRsp, Integer pageNum, Integer pageSize) {

        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 5;
        }
        PageHelper.startPage(pageNum, pageSize);
        return userService.findUser(userRsp);
    }

    /**
     * 修改密码(忘记密码)
     *
     * @param userId
     * @return
     */
    @PostMapping("/user/forget")
    @ApiOperation(value="修改密码(忘记密码)", notes="修改密码(忘记密码)")
    @ApiImplicitParam(paramType="query",name = "userId", value = "用户编号userId", required = true, dataType = "String")
    public RspMsg<User> forgetPassword(String userId) {
        return userService.forgetPassword(userId);
    }

    /**
     * 修改手机号码(忘记密码)
     *
     * @param userId,phone
     * @return
     */
    @PostMapping("/user/forgetphone")
    @ApiOperation(value="修改手机号码", notes="修改手机号码")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "userId", value = "用户编号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query",name = "phone", value = "手机号码", required = true, dataType = "String")
    })
    public RspMsg<User> forgetphone(String userId, String phone) {
        return userService.forgetphone(userId, phone);
    }




    /**
     * 发送短信
     *
     * @throws IOException
     * @throws
     */
    @PostMapping("/trance/sendMsgs")
    @ApiOperation(value="发送短信并返回前台加密过后的codeid", notes="发送短信")
    @ApiImplicitParam(paramType="query",name = "mobile_number", value = "电话号码", required = true, dataType = "String")
    @ResponseBody
    public void sendSMS(String mobile_number) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 手机号解密
        // String phone = Aes.getOldData(mobile_number);
        String yzm = SendSMS.getSjs();
        int result = 0;
        try {
            result = SendSMS.sendSMS(mobile_number, yzm);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject json = new JSONObject();
        if (result > 0) {
            String id = "%$#58412365" + yzm;
            id = Md5Utils.GetMD5Code(id);
            json.put("ifSuccess", true);
            json.put("codeId", id);
        } else {
            json.put("ifSuccess", false);
        }
        out.println(json);
        out.flush();
        out.close();
    }



    /**
     * 注销用户
     *
     * @param userId
     * @return
     */
    @GetMapping("/user/cancelUser")
    @ApiOperation(value="注销用户", notes="注销用户")
    @ApiImplicitParam(paramType="query",name = "userId", value = "用户编号", required = true, dataType = "String")
    public RspMsg<User> cancelUser(String userId) {
        return userService.cancelUser(userId);
    }

    /**
     * 修改登录密码
     *
     * @param
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @PostMapping("/user/updatePassword")
    @ApiOperation(value="修改登录密码", notes="修改登录密码")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "userId", value = "用户编号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query",name = "oldPassword", value = "旧密码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query",name = "newPassword", value = "新密码", required = true, dataType = "String"),

    })
    public RspMsg updatePassword(String userId, String oldPassword, String newPassword) {
        return userService.updatePassword(userId, oldPassword, newPassword);
    }

    @PostMapping("/user/addPayPassword")
    @ApiOperation(value="新增支付密码", notes="新增支付密码")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "payPassWord", value = "支付密码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query",name = "userId", value = "用户编号", required = true, dataType = "String"),
    })
    public RspMsg addPayPassword(String payPassWord, String userId) {
        return userService.addPayPassword(payPassWord, userId);
    }

    /**
     * 修改支付密码
     *
     * @param userId
     * @param oldPayPassword
     * @param newPayPassword
     * @return
     */
    @PostMapping("/user/updatePayPassword")
    @ApiOperation(value="新增支付密码", notes="新增支付密码")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "newPayPassword", value = "新支付密码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query",name = "userId", value = "用户编号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query",name = "oldPayPassword", value = "旧支付密码", required = true, dataType = "String"),

    })
    public RspMsg updatePayPassword(String userId, String oldPayPassword, String newPayPassword) {
        return userService.updatePayPassword(userId, oldPayPassword, newPayPassword);
    }

    /**
     * 充值虚拟币
     *
     * @param
     * @param userId  用户id
     * @param payGold 金币
     * @return
     */
    @PostMapping("/user/addPayGold")

    public RspMsg addPayGold(String userId, String payGold) {
        return userService.addPayGold(userId, payGold);
    }

    //查询用户的基本信息(包括审核通过1,审核不通过2,未审核0)
    @PostMapping("/user/selectByExaminationState")
    @ApiOperation(value="查询用户的基本信息(包括审核通过1,审核不通过2,未审核0)", notes="查询用户的基本信息(包括审核通过1,审核不通过2,未审核0)")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "pageNum", value = "新支付密码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query",name = "pageSize", value = "用户编号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query",name = "phone", value = "旧支付密码", required = true, dataType = "String"),

    })
    public RspMsg<List<User>> selectByExaminationState(Integer pageNum, Integer pageSize, String phone, String examinationState) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 5;
        }
        PageHelper.startPage(pageNum, pageSize);
        return userService.selectByExaminationState(phone, examinationState);
    }

    /**
     * 审核实名认证的信息
     */
    @PostMapping("/user/auditUser")
    public RspMsg<User> auditUser(String userId, String examinationState) {
        return userService.auditUser(userId, examinationState);
    }


    /**
     * 用户身份证件上传
     *
     * @return
     */
    @PostMapping("/user/UploadIDcard")
    @ApiOperation(value="用户身份证件上传", notes="用户身份证件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="user",name = "pageNum", value = "新支付密码", required = true, dataType = "String"),

    })
    public RspMsg<User> UploadIDcard(User user) {
        RspMsg rspMsg = new RspMsg();
        User user1 = userMapper.selectByPrimaryKey(user.getUserId());
        user1.setUserId(user.getUserId());
        user1.setHandheldPhotoPath(user.getHandheldPhotoPath());
        user1.setPositivePhotoPath(user.getPositivePhotoPath());
        user1.setReversePhotoPath(user.getReversePhotoPath());
        int i = userMapper.updateByPrimaryKeySelective(user1);
        if (i > 0) {
            rspMsg.setOK();
            rspMsg.setMsg("保存成功");
        }
        rspMsg.setError();
        rspMsg.setMsg("保存失败");
        return rspMsg;
    }

   /* *//**
     * 用户个人信息保存
     *
     * @return
     *//*
    @PostMapping("/user/PersonaInformation")
    public RspMsg<User> PersonaInformation(User user) {
        RspMsg rspMsg = new RspMsg();
        User user1 = userMapper.selectByPrimaryKey(user.getUserId());
        user1.setExaminationState("0");
        user1.setUserId(user.getUserId());
        user1.setBirthday(user.getBirthday());
        user1.setIdploma(user.getIdploma());
        user1.setGraduateSchool(user.getGraduateSchool());
        user1.setWorkExperienc(user.getWorkExperienc());
        user1.setEmail(user.getEmail());
        user1.setIntroduction(user.getIntroduction());
        user1.setEmergencyPhone(user.getEmergencyPhone());
        user1.setEmergencyContact(user.getEmergencyContact());
        user1.setAddress(user.getAddress());
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i > 0) {
            rspMsg.setOK();
            rspMsg.setMsg("保存成功");
        } else {
            rspMsg.setError();
            rspMsg.setMsg("保存失败");
        }

        return rspMsg;
    }
*/
    /**
     * 手机端根据用户id 查看用户信息
     *
     * @return
     */
    @PostMapping("/user/selectByIdUser")
    public RspMsg<User> selectByIdUser(String userId) {
        RspMsg rspMsg = new RspMsg();
        Example example = new Example(User.class);
        example.or().andEqualTo("userId", userId);
        List<User> users = userMapper.selectByExample(example);
        if (users.size() < 1) {
            rspMsg.setError();
            rspMsg.setMsg("未找到数据");
            return rspMsg;
        }
        User user = userMapper.selectByExample(example).get(0);
        rspMsg.setOK();
        rspMsg.setResult(user);
        return rspMsg;
    }

   /* *//**
     * 手机端根据用户id 查看用户信息
     *
     * @return
     *//*
    @PostMapping("/user/selectUserTalentByIdUser")
    public RspMsg<User> selectUserTalentByIdUser(String userId) {
        RspMsg rspMsg = new RspMsg();
        UserTlent users = userMapper.selectById(userId);
        if (StringUtils.isEmpty(users)) {
            rspMsg.setError();
            rspMsg.setMsg("未找到数据");
            return rspMsg;
        }
        rspMsg.setOK();
        rspMsg.setResult(users);
        return rspMsg;
    }*/
}




